package cn.hfjava.kz.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.common.converter.ByteToBase64Converter;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.tencentcloudapi.common.Credential;
import java.io.IOException;

@RestController
@RequestMapping("/api/v1/ocr")
@Slf4j
@Tag(name = "文字识别")
public class OcrController {


    @Resource
    private Credential credential;


    @Operation(summary = "身份证识别")
    @PostMapping(value = "/idCardNo",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public SaResult queryIDCardOCR(@RequestPart("file") MultipartFile file) throws TencentCloudSDKException, IOException {

        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        OcrClient client = new OcrClient(credential, "ap-guangzhou", clientProfile);

        //将上传的文件转换成base64编码
        String encodeBytesToBase64 = ByteToBase64Converter.encodeBytesToBase64(file.getBytes());


        // 实例化一个请求对象,每个接口都会对应一个request对象
        IDCardOCRRequest req = new IDCardOCRRequest();
        req.setImageBase64(encodeBytesToBase64);
        req.setCardSide("FRONT");
        //req.setConfig("{\"CropIdCard\":true,\"CropPortrait\":true}");
        // req.setImageUrl("https://ltmyblog.oss-cn-shenzhen.aliyuncs.com/myBlog/article/image-20230924213423855.png");

        // 返回的resp是一个GeneralBasicOCRResponse的实例，与请求对象对应
        IDCardOCRResponse resp = client.IDCardOCR(req);
        // 输出json格式的字符串回包
        String jsonResult = AbstractModel.toJsonString(resp);
        log.info("身份证识别响应结果：{}",jsonResult);
        return SaResult.ok("身份证识别成功").setData(resp);
    }
}
